package cn.shengchao.examstar.gankao.infrastrure.service.impl;

import cn.hutool.json.JSONObject;
import cn.shengchao.examstar.gankao.http.GanKaoHttpRequest;
import cn.shengchao.examstar.gankao.http.GanKaoHttpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.shengchao.examstar.gankao.infrastrure.mapper.GkUserMapper;
import cn.shengchao.examstar.gankao.infrastrure.po.GkUser;
import cn.shengchao.examstar.gankao.infrastrure.service.GkUserService;
@Service
public class GkUserServiceImpl extends ServiceImpl<GkUserMapper, GkUser> implements GkUserService{
    @Autowired
    GanKaoHttpUtil ganKaoHttpUtil;

    @Override
    public GkUser getIfExist(Long userId) {
        GkUser gkUser = getOne(Wrappers.lambdaQuery(GkUser.class).eq(GkUser::getUserId, userId));
        if (gkUser != null) {
            return gkUser;
        }else {
            String result=ganKaoHttpUtil.requestCreateUser(userId.toString());
            JSONObject jsonObject= GanKaoHttpRequest.getResultIfSuccess(result);
            if (jsonObject!=null){
                gkUser =new GkUser();
                gkUser.setUserId(userId.toString());
                gkUser.setGkUid(jsonObject.getJSONObject("data").getStr("gankaoUID"));
                gkUser.setMobile(jsonObject.getJSONObject("data").getStr("mobile"));
                gkUser.setPartenerId(jsonObject.getJSONObject("data").getStr("gankaoPartnerUID"));
                save(gkUser);
                return gkUser;
            }
        }
        return null;
    }
}
